from sqlmodel import Session, select, and_, or_
from fastapi import Query
from typing import Annotated, Optional
import models
import utility
from common import exception
from datetime import datetime
from dependencies import engine, SessionDep


"""菜单列表数据

Keyword arguments:
name -- 菜单名称
url -- 菜单url
is_active -- 菜单状态
parent_id -- 父级菜单id
Return: menus -- 菜单列表数据
"""


def get_menu(
    name: str = None,
    url: str = None,
    is_active: bool = None,
    parent_id: int = None,
    user: models.SystemUser = None,
    session: SessionDep = Session(engine),
):
    # 查询条件
    conditions = [
        models.SystemMenu.name == name if name else True,
        models.SystemMenu.url == url if url is not None else True,
        models.SystemMenu.is_active == is_active if is_active is not None else True,
        models.SystemMenu.parent_id == parent_id if parent_id is not None else True,
    ]
    # 查询菜单列表数据
    system_menu = session.exec(
        select(models.SystemMenu)
        .where(and_(*conditions))
        .order_by(models.SystemMenu.order)
    ).all()

    return system_menu


"""新增菜单

Keyword arguments:
menu -- 新增菜单参数
Return: system_menu -- 新增菜单数据
"""


def create_menu(
    menu: models.SystemMenuBase,
    user: models.SystemUser = None,
    session: SessionDep = Session(engine),
):
    system_menu = models.SystemMenu(
        **dict(menu),
        create_id=user.id,
        update_id=user.id,
        createtime=datetime.now(),
        updatetime=datetime.now()
    )
    session.add(system_menu)
    session.commit()
    session.refresh(system_menu)
    return system_menu


"""编辑菜单

Keyword arguments:
id -- 菜单id
menu -- 菜单更新参数
Return: return_description
"""


def update_menu(
    id: int,
    menu: models.SystemMenuBase,
    user: models.SystemUser = None,
    session: SessionDep = Session(engine),
):
    # 查询菜单数据
    system_menu = session.get(models.SystemMenu, id)
    # 如果菜单数据不存在，则抛出异常
    if not system_menu:
        raise exception.create_http_exception(status_code=400, detail="菜单不存在")

    # 更新菜单数据
    system_menu.name = menu.name
    system_menu.icon = menu.icon
    system_menu.url = menu.url
    system_menu.order = menu.order
    system_menu.parent_id = menu.parent_id
    system_menu.is_active = menu.is_active
    system_menu.update_id = user.id
    system_menu.updatetime = datetime.now()
    session.commit()
    session.refresh(system_menu)
    return system_menu


"""删除菜单

Keyword arguments:
id -- 菜单id
Return: return_description
"""


def delete_menu(
    id: int, user: models.SystemUser = None, session: SessionDep = Session(engine)
):
    # 查询菜单数据
    system_menu = session.get(models.SystemMenu, id)
    # 如果菜单数据不存在，则抛出异常
    if not system_menu:
        raise exception.create_http_exception(status_code=400, detail="菜单不存在")
    # 删除菜单数据
    session.delete(system_menu)
    session.commit()
    return system_menu
